import Vue from 'vue';

let userInfo = LA.userInfo;
let permissions = LA.permissions;

function checkUserInfo() {
	if (!userInfo) {
		console.error('[wt-permission] unable to find user info data!');
		return false;
	}
	else {
		return true;
	}
}

/**
 * 获取当前用户的id
 */
function getCurrentUserId() {
	if (!checkUserInfo()) {
		return null;
	}	
	return userInfo['info.id'];
}

/**
 * 获取当前用户的姓名
 */
function getCurrentUserName() {
	if (!checkUserInfo()) {
		return null;
	}
	return userInfo['info.doctor_info'] ? userInfo['info.doctor_info']['name'] : null;
}

/**
 * 获取当前用户的级别
 */
function getCurrentUserGrade() {
	if (!checkUserInfo()) {
		return 999;	// 返回一个大数字，标记最小权限
	}
	let arr = [];
	for (let i=0;i<permissions.length;i++){
		if(permissions[i].indexOf('patient-case-grade') < 0) continue
		let permissCell = permissions[i].split("-")
		if(permissCell.indexOf(window.curModuleName) > -1 && permissCell.indexOf('grade') > -1){
			let value = permissions[i].replace(/[^0-9]/ig,"");
			arr.push(value);
		}
	}
	return Math.min.apply(Math,arr);
	// return Number(userInfo['info.doctor_info']['tech_title']);
}

/**
 * 获取当前用户是否是主管医师
 */
function isCurrentUserManager() {
	return isUserManager(getCurrentUserGrade());
}

/**
 * 判断指定用户是否是主管医师
 * @param {*} user_grade 
 */
function isUserManager(user_grade) {
	return user_grade <= 1;
}

/**
 * 获取当前用户是否是管理员，具有最高级别访问权限
 */
function isAdministrator() {
	return getCurrentUserGrade() == 0;
}

/**
 * 判断用户是否可以修改病例
 * @param {*} caseGrade 
 */
function canEditCase(caseGrade, creator_user_id) {
	console.log(caseGrade, getCurrentUserGrade(), getCurrentUserId(), creator_user_id);
	if (typeof caseGrade == 'string') {
		caseGrade = Number(caseGrade);
	}
	return caseGrade > getCurrentUserGrade() || isAdministrator() || getCurrentUserId() == creator_user_id;
}

function checkPermission(permission) {
	if (LA.permissions) {
		let permissions = LA.permissions;
		for (let i in permissions) {
			if (permissions[i] == permission) {
				console.log('current user has permission ' + permission);
				return true;
			}
		}
		console.log('current user has NOT permission ' + permission);
		return false;
	}
	else {
		console.error('LA.permissions is not defined!');
		return false;
	}
}

export default {
	install: Vue => {
		Vue.prototype.checkPermission = checkPermission;
	},
	checkPermission,
	getCurrentUserName,
	getCurrentUserId,
	getCurrentUserGrade,
	canEditCase,
	isCurrentUserManager
}